<template>
  <div class="min-h-screen bg-gradient-to-br from-purple-50 via-white to-pink-50 flex items-center justify-center px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
      <!-- Logo 和标题 -->
      <div class="text-center">
        <div class="mx-auto h-16 w-16 bg-gradient-to-r from-purple-600 to-pink-600 rounded-full flex items-center justify-center">
          <el-icon :size="28" class="text-white">
            <Key />
          </el-icon>
        </div>
        <h2 class="mt-6 text-3xl font-bold text-gray-900">重置密码</h2>
        <p class="mt-2 text-sm text-gray-600">找回您的账户访问权限</p>
      </div>

      <!-- 重置密码表单 -->
      <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-8">
        <!-- 步骤指示器 -->
        <div class="mb-8">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <div
                :class="[
                  'w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium',
                  currentStep >= 1 ? 'bg-purple-600 text-white' : 'bg-gray-200 text-gray-500'
                ]"
              >
                1
              </div>
              <span class="ml-2 text-sm text-gray-600">验证身份</span>
            </div>
            <div class="flex-1 mx-4 h-px bg-gray-200" />
            <div class="flex items-center">
              <div
                :class="[
                  'w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium',
                  currentStep >= 2 ? 'bg-purple-600 text-white' : 'bg-gray-200 text-gray-500'
                ]"
              >
                2
              </div>
              <span class="ml-2 text-sm text-gray-600">设置新密码</span>
            </div>
          </div>
        </div>

        <el-form
          ref="resetFormRef"
          :model="resetForm"
          :rules="resetRules"
          size="large"
          @submit.prevent="handleSubmit"
        >
          <!-- 第一步：验证身份 -->
          <template v-if="currentStep === 1">
            <!-- 验证方式选择 -->
            <el-form-item>
              <el-radio-group v-model="resetForm.verifyType" class="w-full">
                <el-radio label="email" class="w-1/2">邮箱验证</el-radio>
                <el-radio label="phone" class="w-1/2">手机验证</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 账号输入 -->
            <el-form-item prop="account">
              <el-input
                v-model="resetForm.account"
                :placeholder="resetForm.verifyType === 'email' ? '请输入邮箱地址' : '请输入手机号码'"
                :prefix-icon="resetForm.verifyType === 'email' ? Message : Phone"
                clearable
                class="h-12"
              />
            </el-form-item>

            <!-- 验证码输入 -->
            <el-form-item prop="verifyCode">
              <div class="flex space-x-3">
                <el-input
                  v-model="resetForm.verifyCode"
                  placeholder="请输入验证码"
                  :prefix-icon="Key"
                  clearable
                  class="h-12 flex-1"
                />
                <el-button
                  :disabled="!canSendCode || verifyCodeState.sending"
                  :loading="verifyCodeState.sending"
                  @click="sendVerificationCode"
                  class="h-12 px-6"
                >
                  {{
                    verifyCodeState.sending
                      ? '发送中...'
                      : verifyCodeState.countdown > 0
                      ? `${verifyCodeState.countdown}s`
                      : '发送验证码'
                  }}
                </el-button>
              </div>
            </el-form-item>

            <!-- 下一步按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                :loading="verifying"
                @click="verifyIdentity"
                class="w-full h-12 text-base font-medium"
              >
                {{ verifying ? '验证中...' : '下一步' }}
              </el-button>
            </el-form-item>
          </template>

          <!-- 第二步：设置新密码 -->
          <template v-if="currentStep === 2">
            <!-- 新密码输入 -->
            <el-form-item prop="newPassword">
              <el-input
                v-model="resetForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                :prefix-icon="Lock"
                show-password
                clearable
                class="h-12"
              />
            </el-form-item>

            <!-- 密码强度指示器 -->
            <div v-if="resetForm.newPassword" class="mb-4">
              <div class="flex items-center justify-between text-xs mb-1">
                <span class="text-gray-500">密码强度</span>
                <span :style="{ color: passwordStrength.color }">{{ passwordStrength.text }}</span>
              </div>
              <div class="w-full bg-gray-200 rounded-full h-2">
                <div
                  class="h-2 rounded-full transition-all duration-300"
                  :style="{
                    width: `${(passwordStrength.level / 5) * 100}%`,
                    backgroundColor: passwordStrength.color
                  }"
                />
              </div>
            </div>

            <!-- 确认新密码输入 -->
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="resetForm.confirmPassword"
                type="password"
                placeholder="请确认新密码"
                :prefix-icon="Lock"
                show-password
                clearable
                class="h-12"
                @keyup.enter="handleSubmit"
              />
            </el-form-item>

            <!-- 重置密码按钮 -->
            <el-form-item>
              <div class="flex space-x-3">
                <el-button
                  size="large"
                  @click="goBack"
                  class="flex-1 h-12 text-base"
                >
                  上一步
                </el-button>
                <el-button
                  type="primary"
                  size="large"
                  :loading="loading"
                  @click="handleSubmit"
                  class="flex-1 h-12 text-base font-medium"
                >
                  {{ loading ? '重置中...' : '完成重置' }}
                </el-button>
              </div>
            </el-form-item>
          </template>
        </el-form>

        <!-- 分割线 -->
        <div class="relative my-6">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-gray-300" />
          </div>
          <div class="relative flex justify-center text-sm">
            <span class="px-2 bg-white text-gray-500">或者</span>
          </div>
        </div>

        <!-- 返回登录 -->
        <div class="text-center">
          <span class="text-sm text-gray-600">想起密码了？</span>
          <router-link
            to="/login"
            class="ml-1 text-sm text-blue-600 hover:text-blue-500 font-medium transition-colors"
          >
            返回登录
          </router-link>
        </div>
      </div>

      <!-- 安全提示 -->
      <div class="bg-blue-50 border border-blue-200 rounded-xl p-4">
        <div class="flex items-start">
          <el-icon class="text-blue-600 mt-0.5 mr-3" :size="18">
            <InfoFilled />
          </el-icon>
          <div class="text-sm text-blue-800">
            <p class="font-medium mb-1">安全提示</p>
            <ul class="space-y-1 text-xs">
              <li>• 验证码5分钟内有效，请及时使用</li>
              <li>• 新密码应包含字母和数字，长度至少8位</li>
              <li>• 重置成功后请妥善保管新密码</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Key, Message, Phone, Lock, InfoFilled } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { validators, getPasswordStrength } from '@/utils/auth'
import type { ResetPasswordForm, VerifyCodeState } from '@/types'

// 路由和状态
const router = useRouter()
const authStore = useAuthStore()

// 表单引用
const resetFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)
const verifying = ref(false)
const currentStep = ref(1)

// 表单数据
const resetForm = reactive<ResetPasswordForm>({
  account: '',
  verifyCode: '',
  newPassword: '',
  confirmPassword: '',
  verifyType: 'email'
})

// 验证码状态
const verifyCodeState = reactive<VerifyCodeState>({
  sending: false,
  countdown: 0,
  canSend: true
})

// 计算属性
const canSendCode = computed(() => {
  if (resetForm.verifyType === 'email') {
    return validators.email(resetForm.account) && verifyCodeState.canSend
  } else {
    return validators.phone(resetForm.account) && verifyCodeState.canSend
  }
})

const passwordStrength = computed(() => {
  return getPasswordStrength(resetForm.newPassword)
})

// 表单验证规则
const resetRules: FormRules = {
  account: [
    {
      required: true,
      message: '请输入账号',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (resetForm.verifyType === 'email') {
          if (!validators.email(value)) {
            callback(new Error('请输入有效的邮箱地址'))
          } else {
            callback()
          }
        } else {
          if (!validators.phone(value)) {
            callback(new Error('请输入有效的手机号码'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ],
  verifyCode: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!validators.verifyCode(value)) {
          callback(new Error('验证码格式不正确'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  newPassword: [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    },
    {
      min: 8,
      message: '密码长度不能少于8个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!validators.password(value)) {
          callback(new Error('密码必须包含字母和数字'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: '请确认新密码',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (value !== resetForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

/**
 * 发送验证码
 */
const sendVerificationCode = async () => {
  if (!canSendCode.value) return

  try {
    verifyCodeState.sending = true

    await authStore.sendVerificationCode({
      account: resetForm.account,
      type: resetForm.verifyType
    })

    // 开始倒计时
    startCountdown()

  } catch (error) {
    // 错误处理已在store中完成
    console.error('Send verification code failed:', error)
  } finally {
    verifyCodeState.sending = false
  }
}

/**
 * 开始倒计时
 */
const startCountdown = () => {
  verifyCodeState.countdown = 60
  verifyCodeState.canSend = false

  const timer = setInterval(() => {
    verifyCodeState.countdown--
    
    if (verifyCodeState.countdown <= 0) {
      clearInterval(timer)
      verifyCodeState.canSend = true
    }
  }, 1000)
}

/**
 * 验证身份
 */
const verifyIdentity = async () => {
  if (!resetFormRef.value) return

  try {
    // 验证第一步的字段
    await resetFormRef.value.validateField(['account', 'verifyCode'])
    
    verifying.value = true

    // 这里可以调用验证接口，模拟验证过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 验证成功，进入下一步
    currentStep.value = 2
    ElMessage.success('身份验证成功')

  } catch (error) {
    console.error('Verify identity failed:', error)
    ElMessage.error('验证失败，请检查验证码是否正确')
  } finally {
    verifying.value = false
  }
}

/**
 * 返回上一步
 */
const goBack = () => {
  currentStep.value = 1
  resetForm.newPassword = ''
  resetForm.confirmPassword = ''
}

/**
 * 处理表单提交
 */
const handleSubmit = async () => {
  if (!resetFormRef.value) return

  try {
    // 表单验证
    await resetFormRef.value.validate()
    
    loading.value = true

    // 执行密码重置
    await authStore.resetPassword(resetForm)

    // 重置成功，跳转到登录页
    ElMessage.success('密码重置成功，即将跳转到登录页')
    
    setTimeout(() => {
      router.push({
        path: '/login',
        query: { account: resetForm.account }
      })
    }, 1500)

  } catch (error) {
    // 错误处理已在store中完成
    console.error('Reset password failed:', error)
  } finally {
    loading.value = false
  }
}

// 监听验证类型变化，清空账号和验证码
watch(
  () => resetForm.verifyType,
  () => {
    resetForm.account = ''
    resetForm.verifyCode = ''
  }
)

// 监听新密码变化，清空确认密码
watch(
  () => resetForm.newPassword,
  () => {
    if (resetForm.confirmPassword) {
      resetForm.confirmPassword = ''
    }
  }
)
</script>

<style scoped>
/* 自定义样式 */
.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  border-radius: 8px;
}

.el-button {
  border-radius: 8px;
  font-weight: 500;
}

.el-radio-group {
  display: flex;
  justify-content: space-between;
}

.el-radio {
  margin-right: 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .max-w-md {
    max-width: 100%;
    margin: 0 16px;
  }
  
  .bg-white {
    padding: 24px;
  }
  
  .flex.space-x-3 {
    flex-direction: column;
    space-x: 0;
  }
  
  .flex.space-x-3 > * + * {
    margin-left: 0;
    margin-top: 12px;
  }
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 输入框聚焦效果 */
.el-input:focus-within {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(147, 51, 234, 0.15);
  transition: all 0.2s ease;
}

/* 按钮悬停效果 */
.el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(147, 51, 234, 0.4);
  transition: all 0.2s ease;
}

/* 链接悬停效果 */
a {
  transition: all 0.2s ease;
}

a:hover {
  text-decoration: none;
}

/* 步骤指示器动画 */
.w-8.h-8 {
  transition: all 0.3s ease;
}

/* 密码强度条动画 */
.transition-all {
  transition: all 0.3s ease;
}
</style>
